package com.gui;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

class FileSendThread extends Thread {

	ServerSocket fileTransferServerSocket;
	FileInputStream fis;
	OutputStream os;
	int serverPort;
	String filePath;

	final static int BUFFER_SIZE = 1024 * 4; // 버퍼의 크기이다. 받는쪽과 보내는쪽을 일치시킨다.

	public FileSendThread(String filePath, int serverPort) {
		try {
			fis = new FileInputStream(filePath);

			System.out.println("file transfer socket ready...");
			System.out.println("serverPort = " + serverPort);
			MainWindows.setTextLog("file transfer socket ready...");
			MainWindows.setTextLog("serverPort = " + serverPort);
			fileTransferServerSocket = new ServerSocket(serverPort);

		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
			System.out.println("FileOpen Failure");
			MainWindows.setTextLog("FileOpen Failure");
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public void run() {

		int i;
		byte[] buffer;
		buffer = new byte[BUFFER_SIZE];

		Socket socket = null;

		try {

			System.out.println("wait for client...");
			MainWindows.setTextLog("wait for client...");
			socket = fileTransferServerSocket.accept();
			System.out.println("connection is accepted...");
			MainWindows.setTextLog("connection is accepted...");

			os = socket.getOutputStream();

			while (true) {
				i = fis.read(buffer);
				if (i == -1)
					break;
				System.out.println(i + "Bytes read from file ");
				MainWindows.setTextLog(i + "Bytes read from file ");

				os.write(buffer, 0, i);
				System.out.println(i + "Bytes write to client ");
				MainWindows.setTextLog(i + "Bytes write to client ");
			}
			System.out.println("UploadComplete");
			MainWindows.setTextLog("UploadComplete");
			socket.close();
			fileTransferServerSocket.close();
			fis.close();
		} catch (SocketException se) {
			se.printStackTrace();
			System.out.println("upload canceled!");
			MainWindows.setTextLog("upload canceled!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
